import 'dart:io';

import 'package:fate_blind_box/chat_view/video_push_widget.dart';
import 'package:fate_blind_box/config/app_utils.dart';
import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:fate_blind_box/utils/common_widget.dart';
import 'package:fate_blind_box/utils/provider.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:universal_html/html.dart' as html;

import '../../../network/Api.dart';
import '../../../utils/loading.dart';
import '../../../utils/snack_bar.dart';

//实名认证
class AuthenticationUI extends StatefulWidget {
  const AuthenticationUI({Key? key}) : super(key: key);

  @override
  State<AuthenticationUI> createState() => _AuthenticationState();
}

class _AuthenticationState extends State<AuthenticationUI> {
  final TextEditingController _nameController = TextEditingController();
  final _cardNumController = TextEditingController();
  final List<dynamic?> _avatarList = [];

  String cardFront = '';
  String cardBack = '';
  int uploadCode = -1;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  //上传身份证正反面
  _uploadCard() {
    if (cardFront.isEmpty) {
      toast('请上传身份证正面');
      return;
    }
    if (cardBack.isEmpty) {
      toast('请上传身份证反面');
      return;
    }
    loading(() async {
      final res = await Api.getInstance().uploadCard(cardFront, cardBack);
      print('bbbb $res');
      if (res == null) {
        toast('图片太大或图片上传有误');
        return;
      }
      if (res['code'] == 0 && res['data'] != null) {
        setState(() {
          uploadCode = res['code'];
          _nameController.text = res['data']['name'];
          _cardNumController.text = res['data']['idCardNo'];
        });
      } else {
        toast(res['msg']);
      }
    });
  }

  // 实名认证
  _submit() {
    if (cardFront.isEmpty) {
      toast('请上传身份证正面');
      return;
    }
    if (cardBack.isEmpty) {
      toast('请上传身份证反面');
      return;
    }
    if (_nameController.text.isEmpty) {
      toast('请输入姓名');
      return;
    }
    if (_cardNumController.text.isEmpty) {
      toast('请输入身份证号');
      return;
    }
    print('rrr ${_cardNumController.text} ${_nameController.text}');
    loading(() async {
      final res = await Api.getInstance().idcardIdentify(
          _cardNumController.text,
          _nameController.text,
          Provider.memberId,
          cardFront,
          cardBack);
      final data = res['msg'];
      // ThemeSnackBar.show(context, data);
      toast(data);
      if (res['code'] == 0) {
        Navigator.of(context).pop(true);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    double screenWidth = MediaQuery.of(context).size.width;
    return AppWidget.navTitleBar(
        bgColor: Colors.white,
        title: '实名认证',
        childWidget: GestureDetector(
          onTap: () {
            FocusScope.of(context).unfocus();
          },
          child: SingleChildScrollView(
            child: Column(
              children: [
                const SizedBox(
                  height: 20,
                ),
                GestureDetector(
                  onTap: () {
                    _selectPhoto(context, 'title', screenWidth, '正面');
                  },
                  child: cardFront.isEmpty
                      ? Image.asset(
                          "images/ic_cardfriont.png",
                          width: screenWidth - 28,
                          height: 157,
                          fit: BoxFit.fill,
                        )
                      : Image.file(
                          File(cardFront),
                          width: screenWidth - 28,
                          height: 157,
                          fit: BoxFit.fill,
                        ),
                ),
                const SizedBox(
                  height: 14,
                ),
                GestureDetector(
                  onTap: () {
                    _selectPhoto(context, 'title', screenWidth, '反面');
                  },
                  child: cardBack.isEmpty
                      ? Image.asset(
                          "images/ic_cardback.png",
                          width: screenWidth - 28,
                          height: 157,
                          fit: BoxFit.fill,
                        )
                      : Image.file(
                          File(cardBack),
                          width: screenWidth - 28,
                          height: 157,
                          fit: BoxFit.fill,
                        ),
                ),
                uploadCode == 0
                    ? Container(
                        margin: const EdgeInsets.only(left: 14, top: 20),
                        alignment: Alignment.centerLeft,
                        child: Text(
                          '请确认您的信息是否正确',
                          style: TextStyle(
                              color: ThemeColor.textColorSecond,
                              fontSize: 16,
                              overflow: TextOverflow.ellipsis),
                        ),
                      )
                    : Container(),
                uploadCode == 0
                    ? Container(
                        margin: const EdgeInsets.fromLTRB(14, 12, 14, 0),
                        // height: 50,
                        child: TextField(
                          controller: _nameController,
                          maxLength: 16,
                          obscureText: false,
                          keyboardType: TextInputType.text,
                          cursorColor: ThemeColor.appColor,
                          style: TextStyle(
                              fontSize: 14, color: ThemeColor.textColor),
                          onChanged: (value) {
                            setState(() {
                              _nameController.text = value;
                            });
                          },
                          decoration: InputDecoration(
                            // labelText: '姓名 ',
                            // labelStyle: TextStyle(
                            //     color: ThemeColor.textColorSecond, fontSize: 14),
                            hintText: _nameController.text,
                            counterText: "",
                            border: InputBorder.none,
                            hintStyle:
                                TextStyle(color: ThemeColor.textColorSecond),
                            fillColor: const Color(0xffF1F3FB),
                            filled: true,

                            enabledBorder: const OutlineInputBorder(
                              /*边角*/
                              borderRadius: BorderRadius.all(
                                Radius.circular(5), //边角为30
                              ),
                              borderSide: BorderSide(
                                color: Colors.white54, //边线颜色为黄色
                                // width: 1, //边线宽度为2
                              ),
                            ),
                            focusedBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(5),
                              borderSide: const BorderSide(
                                color: Colors.white54, //边框颜色为绿色
                                width: 1, //宽度为5
                              ),
                            ),
                            contentPadding: const EdgeInsets.only(
                                top: 0, bottom: 0, left: 10),
                          ),
                        ),
                      )
                    : Container(),
                uploadCode == 0
                    ? Container(
                        margin: const EdgeInsets.fromLTRB(14, 12, 14, 0),
                        // height: 50,
                        child: TextField(
                          controller: _cardNumController,
                          maxLength: 22,
                          obscureText: false,
                          keyboardType: TextInputType.text,
                          cursorColor: ThemeColor.appColor,
                          style: TextStyle(
                              fontSize: 14, color: ThemeColor.textColor),
                          onChanged: (value) {
                            setState(() {
                              _cardNumController.text = value;
                            });
                          },
                          decoration: InputDecoration(
                            // labelText: '身份证号 ',
                            // labelStyle: TextStyle(
                            //     color: ThemeColor.textColorSecond, fontSize: 14),
                            hintText: _cardNumController.text,
                            counterText: "",
                            border: InputBorder.none,
                            hintStyle:
                                TextStyle(color: ThemeColor.textColorSecond),
                            fillColor: const Color(0xffF1F3FB),
                            filled: true,

                            enabledBorder: const OutlineInputBorder(
                              /*边角*/
                              borderRadius: BorderRadius.all(
                                Radius.circular(5), //边角为30
                              ),
                              borderSide: BorderSide(
                                color: Colors.white54, //边线颜色为黄色
                                // width: 1, //边线宽度为2
                              ),
                            ),
                            focusedBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(5),
                              borderSide: const BorderSide(
                                color: Colors.white54, //边框颜色为绿色
                                width: 1, //宽度为5
                              ),
                            ),
                            contentPadding: const EdgeInsets.only(
                                top: 0, bottom: 0, left: 10),
                          ),
                        ),
                      )
                    : Container(),
                const SizedBox(
                  height: 30,
                ),
                GestureDetector(
                    onTap: () {
                      FocusScope.of(context).unfocus();
                      if (uploadCode == 0) {
                        _submit();
                      } else {
                        _uploadCard();
                      }
                    },
                    child: Container(
                        height: 44,
                        margin: const EdgeInsets.symmetric(
                            horizontal: 12, vertical: 24),
                        decoration: ShapeDecoration(
                            shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(22)),
                            color: ThemeColor.appColor),
                        alignment: Alignment.center,
                        child: Text(
                          uploadCode == 0 ? '确认提交' : "上传",
                          style: const TextStyle(color: Colors.white),
                        ))),
              ],
            ),
          ),
        ));
  }

  /// 权限检查
  _checkPermissions(String type, String cardType) async {
    Navigator.pop(context);
    var permissions = [];
    if (type == '拍照') {
      permissions.add(Permission.camera);
    } else {
      if (Platform.isAndroid) {
        permissions.add(AppUtils.getPhotoPermission());
      } else if (Platform.isIOS) {
        permissions.add(Permission.photos);
      }
    }
    // 用户拒绝的权限
    List<Permission> missed = [];
    for (var permission in permissions) {
      if (permission == Permission.camera) {
        var status = await Permission.camera.status;
        if (status != PermissionStatus.granted) {
          missed.add(permission);
        }
      } else {
        if (Platform.isIOS) {
          var status = await Permission.photos.status;
          if (status != PermissionStatus.granted) {
            missed.add(permission);
          }
        }
        if (Platform.isAndroid) {
          Permission permission = await AppUtils.getPhotoPermission();
          var status = await permission.status;
          if (status != PermissionStatus.granted) {
            missed.add(permission);
          }
        }
      }
    }
    bool allGranted = missed.isEmpty;
    if (Platform.isAndroid && missed.isNotEmpty) {
      var action = await permissionDialog(
        context,
        title: "“都肆商圈”需要使用您的${type == '拍照' ? '相机' : '相册'}，是否允许？",
        content: '不允许将无法为您提供实名认证服务',
      );
      if (action != '允许') {
        return;
      }
    }
    Map<Permission, PermissionStatus> allStatus = await missed.request();
    allGranted = true;
    for (var status in allStatus.values) {
      if (status != PermissionStatus.granted) {
        allGranted = false;
      }
    }
    if (allGranted) {
      _checkAvatar(type, cardType);
    }
  }

  _checkAvatar(String type, String cardType) {
    ImageSource source;
    if (type == '拍照') {
      source = ImageSource.camera;
    } else {
      source = ImageSource.gallery;
    }
    if (!kIsWeb) {
      loading(() async {
        final picker = ImagePicker();
        final pickerFile = await picker.pickImage(source: source);
        if (pickerFile != null) {
          print('cccc   ${pickerFile.path}');
          setState(() {
            if (cardType == '正面') {
              cardFront = pickerFile.path;
            } else {
              cardBack = pickerFile.path;
            }
          });
        }
      });
    } else {
      final uploadInputElement = html.FileUploadInputElement();
      uploadInputElement.multiple = false;
      uploadInputElement.draggable = true;
      uploadInputElement.click();
      uploadInputElement.onChange.listen((event) {
        final file = uploadInputElement.files?.first;
        if (file != null) {
          loading(() async {
            final formData = html.FormData();
            formData.appendBlob("avatarfile", file.slice(), file.name);
            formData.append("memberId", Provider.memberId);
            Api.getInstance().uploadAvatarFromHtml(formData, (e) {
              if (e['code'] == 0) {
                setState(() {
                  // _user['profilePhoto'] = e['data']['url'];
                });
              } else {
                ThemeSnackBar.show(context, e['msg']);
              }
            });
          });
        }
      });
    }
  }

  Future<void> _selectPhoto(
      context, String title, double width, String cardType) async {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return SafeArea(
          bottom: true,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              GestureDetector(
                  onTap: () {
                    _checkPermissions('拍照', cardType);
                  },
                  child: Container(
                    alignment: Alignment.center,
                    width: width,
                    height: 55.w,
                    color: Colors.white,
                    child: const Text('拍照'),
                  )),
              Divider(
                color: ThemeColor.sendMsgColor,
                height: 1.w,
              ),
              GestureDetector(
                  onTap: () {
                    _checkPermissions('相册', cardType);
                  },
                  child: Container(
                    alignment: Alignment.center,
                    width: width,
                    height: 60.w,
                    color: Colors.white,
                    child: const Text('从手机相册选择'),
                  )),
              Divider(
                color: ThemeColor.sendMsgColor,
                thickness: 7,
                height: 1.w,
              ),
              GestureDetector(
                  onTap: () {
                    Navigator.pop(context);
                  },
                  child: Container(
                    alignment: Alignment.center,
                    width: width,
                    height: 55.w,
                    child: const Text('取消'),
                  ))
            ],
          ),
        );
      },
    );
  }
}
